//
//  RichTextViewController.m
//  whatever
//
//  Created by 李培根 on 2020/12/22.
//  Copyright © 2020 李培根. All rights reserved.
//

#import "RichTextViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WKNavigationAction.h>
#import <WebKit/WKWindowFeatures.h>
#import <WebKit/WKFrameInfo.h>
#import <WebKit/WKNavigationDelegate.h>
#import <WebKit/WKUIDelegate.h>

NSString * fit_rich_web(void);

@interface RichTextViewController ()<WKNavigationDelegate,WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;
@end

@implementation RichTextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.cyanColor;
    NSError *error = nil;
    //http://81.71.125.249/list/edit
    NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://81.71.125.249/api/cs/getEditData"] encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"error = %@", error);
    }
    NSDictionary *info = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
    NSLog(@"info = %@", info);
    
    NSString *htmlContent = info[@"data"];
    NSString *fitHtml = fit_rich_web();
    if (![htmlContent containsString:@"<head"]) {
        if ([htmlContent containsString:@"<body"]) {
            htmlContent = [fitHtml stringByReplacingOccurrencesOfString:@"htmlContent" withString:htmlContent];
        } else {
            NSString *bodyHtml = [NSString stringWithFormat:@"<body>%@</body>", htmlContent];
            htmlContent = [fitHtml stringByReplacingOccurrencesOfString:@"htmlContent" withString:bodyHtml];
        }
    }
    [self testWKWebViewWithHTMLStr:htmlContent];
}

- (void)testWKWebViewWithHTMLStr:(NSString *)htmlStr {
    [self.webView loadHTMLString:htmlStr baseURL:nil];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    NSLog(@"%@", navigationAction.request);
    if (!navigationAction.targetFrame.isMainFrame) {
        
        [webView loadRequest:navigationAction.request];
        
    }
    
    return nil;
}

- (WKWebView *)webView {
    if (_webView == nil) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    }
    return _webView;
}

@end


NSString * fit_rich_web(void)
{
#define __wvjb_js_func__(x) #x
    static NSString * html = @__wvjb_js_func__(
     <!DOCTYPE html>
     <html>
     <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
     
     <title></title>
     </head>
    htmlContent
    </html>
     
     );
#undef __wvjb_js_func__
    return html;
};
